# coding: utf-8

import tornado
import datetime
from handlers.base import BaseHandler

class RecentMeasureHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        # 首页的近期测量
        try:
            rid = self.get_query_argument('rid')
        except Exception as err:
            print(err)
            self.response_msg(400, '请求参数错误')
        if 'page' in self.request.arguments:
            # 获取到最近一次记录向前10天的记录
            page = self.get_query_argument('page')
            try:
                page = int(page)
            except Exception as err:
                page = 1
            date_list = []
            measure_list = []
            response_list = []
            # 查询最后一条数据的测量时间
            last_measure = yield self.db.HMMeasure.find({'role': rid}).sort('created_at', -1).limit(1).to_list(1)
            if last_measure:
                last_day = last_measure[0]['created_at'].replace(hour=0, minute=0, second=0) + datetime.timedelta(1)
            else:
                self.response_msg(200, '没有更多数据了')
                return
            # 查询的限制条件
            from_datetime = last_day - datetime.timedelta(10*page)
            to_datetime = from_datetime + datetime.timedelta(10)
            # 开始查询
            measure = self.db.HMMeasure.find({'role': rid, 'created_at': {'$gt': from_datetime, '$lt': to_datetime}})\
                                       .sort('created_at', -1)
            # 把测量的日期提取出来
            while (yield measure.fetch_next):
                item = measure.next_object()
                if item['created_at'].date() not in date_list:
                    date_list.append(item['created_at'].date())
                measure_list.append(item)
            # 把测量的数据按照日期分类
            for item in date_list:
                content = {}
                content['date'] = str(item)
                content['data'] = []
                for data in measure_list:
                    if item == data['created_at'].date():
                        dic = {}
                        if 'sugar' == data['measureType']:
                            dic['title_name'] = '血糖' + '(' + data['timePoint'] + ')'
                            dic['value'] = str(data['sugarValue']) + 'mmol/L'
                            if data['timePoint'] == '早餐前':
                                dic['reference'] = '3.9~6.1mmol/L'
                            elif data['timePoint'] == '早餐后' or data['timePoint'] == '午餐后' or data['timePoint'] == '晚餐后':
                                dic['reference'] = '<7.8mmol/L'
                            else:
                                dic['reference'] = '<11.1mmol/L'
                        elif 'pressure' == data['measureType']:
                            dic['title_name'] = '血压'
                            dic['value'] = '' + str(data['pressureLow']) + '/' + str(data['pressureHigh']) + 'mmHg'
                            dic['reference'] = '90~140/60~90mmHg'
                        elif 'bmi' == data['measureType']:
                            dic['title_name'] = 'BMI指数'
                            dic['value'] = str(data['bmiValue'])
                            dic['reference'] = '18.5~24.99'
                        else:
                            print('measureType错误')
                        content['data'].append(dic)
                response_list.append(content)
            if len(response_list) < 1:
                self.response_msg(200, '没有更多数据了')
            else:
                self.response_msg(200, '获取分页数据成功', response_list)

        else:
            # 获取前4条数据
            measure = self.db.HMMeasure.find({'role': rid}).sort('created_at', -1).limit(4)
            result = []
            while (yield measure.fetch_next):
                item = measure.next_object()
                dic = {}
                if item['measureType'] == 'sugar':
                    dic['title_name'] = '血糖' + item['timePoint']
                    dic['value'] = str(item['sugarValue']) + 'mmol/L'
                    dic['create_at'] = self.format_datetime(item['created_at'])
                elif item['measureType'] == 'pressure':
                    dic['title_name'] = '血压'
                    dic['value'] = '' + str(item['pressureLow']) + '/' + str(item['pressureHigh']) + 'mmHg'
                    dic['create_at'] = self.format_datetime(item['created_at'])
                elif item['measureType'] == 'bmi':
                    dic['title_name'] = 'BMI指数'
                    dic['value'] = str(item['bmiValue'])
                    dic['create_at'] = self.format_datetime(item['created_at'])
                else:
                    print(item, 'item type wrong sugar/pressure/bmi')
                result.append(dic)
            if len(result) < 1:
                self.response_msg(200, '您还没有测量数据')
            else:
                self.response_msg(200, '最近的4条测量数据', result)
